<?php
/**
 * 蜗牛博客
 * 本文件内代码属于“蜗牛博客”项目，禁止修改再发布本程序源码，禁止去除页面底部的版权申明。所有版权保留
 * User: upliu
 * Email: 753073861@qq.com
 * QQ: 753073861
 * 程序主页：http://demo.upliu.net/snail-blog/
 */

require __DIR__.'/init.php';

check_login();

$db = Db::getInstance();

switch (get('action')) {
    case 'edit':
        $post = $db->query("select * from post where id=?", get('id'));
        if (empty($post)) {
            snail_alert('文章不存在');
        }
        $rows = $db->queryAll("select tag_id from map_post_tag where post_id=?", $post['id']);
        $tag_ids = array_column($rows, 'tag_id');
        $rows = $db->queryAllWhereIn("select name from tag", 'id', $tag_ids);
        $post['tag'] = implode(',', array_column($rows, 'name'));
        echo renderWithLayout('post-edit', array('post' => $post));
        break;


    case 'delete':
        it_must_post();
        $count = $db
            ->delete('post', 'id=?', get('id', 0));
        if ($count > 0) {
            set_success_message('删除成功');
        } else {
            set_success_message('删除失败');
        }

        redirect_path('post.php');
        break;


    case 'save':
        $data = array_map(function($v){return trim($v);}, $_POST);
        if (empty($data['post_title']) || empty($data['post_content'])) {
            echo_json_error('标题和内容不能为空');
        }
        if (strlen($data['post_password']) > 20) {
            echo_json_error('密码长度不能超过20');
        }
        $data['post_author_id'] = get_current_login_user_info('id');

        $id = post_save($data);
        if (empty($data['id'])) {
            echo_json_success('', '', 'post.php?action=edit&id=' . $id);
        } else {
            echo_json_success();
        }
        break;


    default:
        if ($tag_id = get('tag_id')) {
            $count = $db->queryColumn("select count(1) from post join map_post_tag on post.id=map_post_tag.post_id where tag_id=?", $tag_id);
            $page_size = 15;
            $offset = (get('_page', 1) - 1) * $page_size;
            $pagination = pagination('', $count, $page_size, '');
            $items = $db->queryAll("select post.* from post join map_post_tag on post.id=map_post_tag.post_id where tag_id=? limit $offset,$page_size", $tag_id);
            $data = array(
                'items' => $items,
                'pagination' => array(
                    'html' => $pagination,
                    'count' => $count
                ),
            );
        } else {
            if ($m = get('m')) {
                $s = $m . '-01 00:00:00';
                $e = $m . '-31 23:59:59';
            } else {
                $s = $e = '';
            }

            $where = array(
                'category_id' => get('cid'),
                'post_date >=' => $s,
                'post_date <=' => $e,
                'post_title like' => get('s'),
                'order by id desc'
            );

            $data = $db->getList('post', $where);
        }

        $author_ids = array_unique(array_column($data['items'], 'post_author_id'));
        $rows = $db->queryAllWhereIn("select id,username from user", 'id', $author_ids);
        $users = array_index($rows, 'id', true);

        $post_ids = array_column($data['items'], 'id');
        $category_ids = array_unique(array_column($data['items'], 'category_id'));

        $rows = $db->queryAllWhereIn('select id,name from category', 'id', $category_ids);
        $category_name_map = array_column($rows, 'name', 'id');

        $rows = $db->queryAllWhereIn('select post_id,tag_id from map_post_tag', 'post_id', $post_ids);
        $post_tags = array_index($rows, 'post_id');
        $tag_ids = array_column($rows, 'tag_id');

        $rows = $db->queryAllWhereIn('select id,name from tag', 'id', $tag_ids);
        $tag_name_map = array_column($rows, 'name', 'id');

        foreach ($data['items'] as &$post) {

            if (!empty($post_tags[$post['id']])) {
                $post['tag'] = implode('、', array_map(function($pt) use ($tag_name_map){
                    $tag_id = $pt['tag_id'];
                    return "<a href='?tag_id=$tag_id'>".hsc($tag_name_map[$tag_id])."</a>";
                }, $post_tags[$post['id']]));
            } else {
                $post['tag'] = '—';
            }

            if ($post['comment_count'] > 0) {
                $post['comment'] = "<a href='comment.php?post_id={$post['id']}'>{$post['comment_count']}</a>";
            } else {
                $post['comment'] = '—';
            }
        } unset($post);

        echo renderWithLayout('post', array(
            'data' => $data,
            'users' => $users,
            'category_name_map' => $category_name_map
        ));
        break;
}
